package com.ys.chatserver.rtc;

import com.alibaba.fastjson.JSONObject;
import com.eva.epc.common.file.FileHelper;
import com.eva.framework.dbpool.DBDepend;
import com.eva.framework.utils.LoggerFactory;
import com.google.gson.Gson;
import com.ys.chatserver.http.logic.LogicProcessor2;
import com.ys.chatserver.http.logic.dto.PttFileBean;
import com.ys.chatserver.im.ChatServerEventListener;
import com.ys.chatserver.im.ChatServerLauncher;
import com.ys.chatserver.im.dto.MsgBody4Group;
import com.ys.chatserver.im.dto.MsgBodyRoot;
import com.ys.chatserver.im.dto.MsgType;
import com.ys.chatserver.im.impl.MessageRecordManager;
import com.ys.chatserver.im.impl.OfflineMessageManager;
import com.ys.chatserver.im.impl.UsersStatusManager;
import com.ys.chatserver.im.util.MessageHelper;
import com.ys.chatserver.tool.EmptyUtils;
import com.ys.chatserver.tool.VideoUtils;
import net.ys.mobileimsdk.server.protocal.Protocal;
import org.slf4j.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.Vector;

public class RtcMP4NotifyServlet extends HttpServlet {

    Logger logger = LoggerFactory.getLog();

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            String queryString = req.getQueryString();
            String authToken;
            String time;
            String token = req.getParameter("token");
            if (Objects.isNull(token)) {
                token = req.getHeader("token");
                time = req.getHeader("time");
                authToken = req.getHeader("authToken");
            } else {
                time = req.getParameter("time");
                authToken = req.getParameter("authToken");
                queryString = queryString.substring(0, queryString.indexOf("&token"));
            }
            String path = String.format("/api/%s?%s", getServletName(), queryString);
            logger.info("--------------------------path:{}------time:{}-----token:{}------authToken:{}--------------------------", path, time, token, authToken);
            dispatch(JSONObject.parseObject(req.getReader().readLine(), RtcMP4Notify.class), resp);
        } catch (Exception e) {
            logger.error("message:" + e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    protected void dispatch(RtcMP4Notify prRequest, HttpServletResponse resp) throws Exception {
        logger.info("-------------------------------------------------------------------mp4---------------------------------------------------------");
        UsersStatusManager liverUsersMgr = ChatServerEventListener.getInstance().getLiverUsersMgr();
        String app = prRequest.getApp();
        if (app.equals(ConstRtcApp.APP_PTT)) {
            //对讲文件
            String stream = prRequest.getStream();
            if (EmptyUtils.isNotEmpty(stream)) {
                String[] strings = stream.split("-");
                if (strings.length >= 1) {
                    String groupId = stream.contains("ONEKEY") || stream.contains("SOS") ? strings[2] : strings[1];
                    String[] arr = groupId.split("_");
                    String userId = stream.contains("ONEKEY") || stream.contains("SOS") ? strings[4] : strings[3];
                    String sql;
                    if (stream.contains("ONEKEY")) {
                        Vector<Vector<?>> node = LogicProcessor2.db.queryData("select s_ids,level from chat_group_node where node_id =  '" + arr[1] + "' and base_id = '" + arr[0] + "' and g_status = 1 and node_type = 'MAIN_CHANNEL'");
                        String nodeSids = node.get(0).get(0).toString();
                        String level = node.get(0).get(1).toString();
                        sql = "select  DISTINCT user_uid from chat_group_node where level > " + level + " and  base_id = '" + arr[0] + "' and node_type = 'USER' and s_ids like '%" + nodeSids + "%' and s_ids like '%," + userId + ",%' and g_status = 1";
                    } else {
                        sql = "select user_uid from chat_group_node where base_id = '" + arr[0] + "' and node_pid = '" + arr[1] + "' and g_status = 1 and node_type = 'USER'";
                    }
                    String fp = Protocal.genFingerPrint();
                    Vector<Vector<?>> vectors = LogicProcessor2.db.queryData(sql);
                    MsgBody4Group msgBody4Group = new MsgBody4Group();
                    msgBody4Group.setTy(MsgType.TYPE_PTT);
                    msgBody4Group.setParentFp(fp);
                    msgBody4Group.setT(groupId);
                    msgBody4Group.setF(userId);
                    Vector<Vector<?>> vectorName = LogicProcessor2.db.queryData("select nickname from g_users where  del_flag = 0 and user_uid='" + userId + "'");
                    if (!vectorName.isEmpty()) {
                        msgBody4Group.setNickName(vectorName.get(0).get(0).toString());
                    }

                    PttFileBean fileBean = new PttFileBean();
                    fileBean.setFileName(prRequest.file_name);
                    fileBean.setFileLength(prRequest.file_size);
                    fileBean.setUrl(prRequest.getUrl());
                    msgBody4Group.setM(new Gson().toJson(fileBean));

                    String time = String.valueOf(System.currentTimeMillis());
                    msgBody4Group.setM3(time);

                    for (Vector<?> vector : vectors) {
                        String str = vector.get(0).toString();
                        boolean isOnline = liverUsersMgr.isOnline(str);
                        MessageHelper.SendResultObserver sendResultObserver = (code, p) -> {
                            // 返回值true：对于应用层逻辑来说，无论是在线发送成功，或者是跨服桥接成功，都算是发送成功
                            if (code) {
                                if (!isOnline && ChatServerLauncher.bridgeEnabled) {
                                    // 尝试进行app端的push通知
                                    OfflineMessageManager.processOfflineMessage(p, false, time); // 注意此参数为true！
                                }

                            } else {// 返回值false：实时或桥接发送没有成功（需要离线处理）
                                OfflineMessageManager.processOfflineMessage(p, false, time);
                            }
                        };
                        MessageHelper.sendGroupPttMsg_SERVER$TO$B_Message(str, msgBody4Group, sendResultObserver);
                    }
                    MessageRecordManager.colectMsgAsync(
                            userId
                            , groupId
                            , MsgBodyRoot.CHAT_TYPE_GROUP$CHAT
                            , MsgBodyRoot.TYPE_PTT + ""
                            , new Gson().toJson(fileBean)
                            , fp
                            , fp);
                }
            }
        } else if (app.equals(ConstRtcApp.APP_LIVE)) {
            //实时视频存档
            //实时视频存档
            LoggerFactory.getLog().info("----------rtcmp5notifyservlet-live:{}---------", new Gson().toJson(prRequest));
            String stream = prRequest.getStream();
            if (EmptyUtils.isNotEmpty(stream)) {
                String[] strings = stream.split("-");
                if (strings.length >= 1) {
                    if (strings.length == 2) {
                        String userId = strings[0];
                        String groupId = LogicProcessor2.db.queryData("select base_id from chat_group_node where user_uid = '" + userId + "' and g_status = 1 and node_type =  'USER'").get(0).get(0).toString();
                        // 保存实时视频信息到库
                        syncLiveVideo(prRequest.url, prRequest.file_size, userId, groupId);
                    } else {
                        String groupId = strings[1];
                        String userId = strings.length == 4 ? strings[2] : strings[3];
                        // 保存实时视频信息到库
                        syncLiveVideo(prRequest.url, prRequest.file_size, userId, groupId);
                    }


                    // 取首贞图
                    new Thread(() -> {
                        try {
                            LoggerFactory.getLog().info("-------prRequest:{}----------", prRequest);
                            firstFrameImage(prRequest.file_path, prRequest.file_name);
                        } catch (Exception e) {
                            LoggerFactory.getLog().error("-------livevideo get first frame fail-------", e);
                        }
                    }).start();
                }
            }
        }
        String str = RtcCommonAck.authSuccess();
        LoggerFactory.getLog().info("[RtcMP4Notify]   -> " + prRequest + ",<- " + str);
        resp.getWriter().write(str);
        resp.setStatus(200);
    }

    private void syncLiveVideo(String fileName
            , long file_size, String user_id, String groupId) throws Exception {
        logger.info("----------rtcmp5notifyservlet-syncLiveVideo ---------");

        // 已经存在这条记录了
        if (!LogicProcessor2.db.queryData("select 1 from t_cloud where file_name='"
                + fileName + "' and create_uid='"
                + user_id + "' and g_id='"
                + groupId + "' and store_type = 1").isEmpty()) {
            LogicProcessor2.db.update("update t_cloud set file_name=?"
                            + ",file_size=?,update_time=" + DBDepend.getDefaultDatetimeFunc()
                            + ",g_id=?, create_uid=? where file_name=? and store_type = 1"
                    , new Object[]{fileName, file_size, groupId, user_id, fileName}, false);
        } else {
            LogicProcessor2.db.update(
                    "INSERT INTO t_cloud(file_name" +
                            ",file_size,file_type,create_time,create_uid,g_id,store_type) " +
                            "VALUES(?,?,?," + DBDepend.getDefaultDatetimeFunc() + ",?,?,?)"
                    , new Object[]{fileName, file_size, 1, user_id, groupId, 1}
                    , false);
        }
    }

    /**
     * 存放首贞图
     * /disk/vdisk1/zlmediakit/zlmediakit/www/record/live//2023-12-28/20231228173051_5123_73f0395b960ea630a802f36be4d1f611_USER-033621208472-400206-1703755851452_0.mp4
     */
    private void firstFrameImage(String path, String name) throws Exception {
        logger.info("--------firstFrameImage start--------");
        String foldPath = path.substring(0, path.indexOf(name) - 1);
        String jpgName = FileHelper.getFileNameWithoutExt(name) + ".jpg";
        File thumbFile = new File(foldPath, jpgName);
        VideoUtils.getThumbnail(new File(path), thumbFile);
    }

}
